package com.desktopmng.action;

import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.json.JSONArray;
import org.json.JSONObject;

import com.desktopmng.orm.CalendarPO;
import com.desktopmng.core.ServiceManager;
import com.desktopmng.core.utils.DateUtils;
import com.desktopmng.core.utils.Struts2Utils;
import com.desktopmng.orm.CalendarViewFormat;
import com.desktopmng.service.CalendarManager;

@SuppressWarnings("serial")
@Results( { @Result(value = "/common/message.jsp"),
		@Result(name = "searchinfoinit", value = "/resources/jsp/calendar.jsp"),
		@Result(name = "modifyInfo", value = "/resources/jsp/login1.jsp"),
		@Result(name = "saveInfo", value = "/resources/jsp/main.jsp") })
public class CalendarAction extends BaseJsonAction {
	
	public static final String GOOGLECALENDARURL = "https://www.googleapis.com/calendar/v3/calendars/micheallee98@gmail.com/events?access_token=";
	
	private CalendarManager calendarManager = (CalendarManager) ServiceManager.getBean("calendarManager");

	public String searchinfoinit() {
		String access_token = request.getParameter("access_token");
//		String token_type = request.getParameter("token_type");
//		String expires_in = request.getParameter("expires_in");
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpGet httpget = new HttpGet(GOOGLECALENDARURL + access_token);
			httpget.addHeader("Content-Type", "text/xml");
			HttpResponse response = httpclient.execute(httpget);
			HttpEntity resEntity = response.getEntity();
			InputStreamReader reader = new InputStreamReader(
					resEntity.getContent(), "UTF-8");
			char[] buff = new char[1024];
			StringBuffer sb = new StringBuffer();
			int length = 0;
			while ((length = reader.read(buff)) != -1) {
				sb.append(new String(buff, 0, length));
			}
			
			JSONObject jsonobject = new JSONObject(sb.toString());
			TimeZone now = TimeZone.getDefault();
			if (jsonobject.has("timeZone")) {
				now = TimeZone.getTimeZone((String) jsonobject.get("timeZone"));
			}
			int clientzone = now.getRawOffset()/3600000;
			Date start = new Date();
			Date end = new Date();
			int isAllDayEvent = 0;
			if (jsonobject.has("items")) {
				JSONArray array = jsonobject.getJSONArray("items");
				JSONObject object = null;
				CalendarPO c = new CalendarPO();
				List<CalendarPO> list = new ArrayList<CalendarPO>();
				for (int i = 0; i < array.length(); i++) {
					object = array.getJSONObject(i);
					if (object.has("summary")) {
						c.setSubject(object.get("summary").toString());
					}
					if (object.has("location")) {
						c.setLocation(object.get("location").toString());
					}
					if (object.has("description")) {
						c.setDescription(object.get("description").toString());
					}
					if (object.has("colorId")) {
						c.setCategory(object.get("colorId").toString());
					}
					if (object.has("start")) {
						JSONObject startobj = object.getJSONObject("start");
						if (startobj.has("date")) {
							isAllDayEvent = 1;
							start = DateUtils.getFormateDate(startobj.get("date").toString(), "yyyy-MM-dd");
						} else if(startobj.has("dateTime")) {
							start = DateUtils.getFormateDate(startobj.get("dateTime").toString(), "yyyy-MM-dd'T'HH:mm:ss");
						}
						c.setStartTime(start);
					}
					if (object.has("end")) {
						JSONObject endobj = object.getJSONObject("end");
						if (endobj.has("date")) {
							end = start;
						} else if(endobj.has("dateTime")) {
							end = DateUtils.getFormateDate(endobj.get("dateTime").toString(), "yyyy-MM-dd'T'HH:mm:ss");
						}
						c.setEndTime(end);
					}
					c.setIsAllDayEvent(isAllDayEvent);
					c.setUserId("1");
					c.setTimeZone(clientzone);
					c.setUpTime(new Date());
					list.add(c);
					c = new CalendarPO();
				}
				calendarManager.addCalendarBatch(list);
			}
			
		} catch(Exception e) {
			
		}
		return SEARCHINFOINIT;
	}
	
	public void getPersonalCalendarData() {
		String showdate = request.getParameter("showdate");
		String viewtype = request.getParameter("viewtype");
		String timezone = request.getParameter("timezone");
		String weekstartday = request.getParameter("weekstartday");
		Date date = DateUtils.getFormateDate(showdate, "dd/MM/yyyy");
		int clientzone = Integer.parseInt(timezone);
        int serverzone = getTimeZone();
        int zonediff = serverzone - clientzone;
        CalendarViewFormat form = new CalendarViewFormat(viewtype, date, Integer.parseInt(weekstartday));
        Date qstart = DateUtils.addHours(form.getStartDate(), zonediff);
        Date qend = DateUtils.addHours(form.getEndDate(), zonediff);
        List<CalendarPO> list = calendarManager.queryCalendars(DateUtils.getFormateDate(qstart), DateUtils.getFormateDate(qend), "1");
        List<Object[]> data = ConvertToStringArray(list);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("events", data);
        map.put("issort", true);
        map.put("start", qstart.getTime());
        map.put("end", qend.getTime());
        map.put("error", null);
        JSONObject object = new JSONObject(map);
		Struts2Utils.renderJson(object.toString());
	}
	
	public void quickAddPersonalCal() {
		String subject = request.getParameter("CalendarTitle");
		String strStartTime = request.getParameter("CalendarStartTime") + ":00";
		String strEndTime = request.getParameter("CalendarEndTime") + ":00";
		String isallday = request.getParameter("IsAllDayEvent");
		String timezone = request.getParameter("timezone");
		int clientzone = Integer.parseInt(timezone);
        int serverzone = getTimeZone();
        int zonediff = serverzone - clientzone;
        Date start = DateUtils.getFormateDate(strStartTime, "dd/MM/yyyy HH:mm:ss");
        Date end = DateUtils.getFormateDate(strEndTime, "dd/MM/yyyy HH:mm:ss");
		CalendarPO c = new CalendarPO();
		c.setUserId("1");
		c.setSubject(subject);
		c.setStartTime(DateUtils.addHours(start, zonediff));
		c.setEndTime(DateUtils.addHours(end, zonediff));
		c.setIsAllDayEvent(Integer.parseInt(isallday));
		c.setInstanceType(0);
		c.setUpTime(new Date());
		Long id = calendarManager.addCalendar(c);
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("Data", id);
        map.put("IsSuccess", true);
        map.put("Msg", "the calendar saved");
        JSONObject object = new JSONObject(map);
		Struts2Utils.renderJson(object.toString());
	}
	
	public void quickUpdatePersonalCal() {
		String Id = request.getParameter("calendarId");
		String strStartTime = request.getParameter("CalendarStartTime") + ":00";
		String strEndTime = request.getParameter("CalendarEndTime") + ":00";
        String timezone = request.getParameter("timezone");
		int clientzone = Integer.parseInt(timezone);
        int serverzone = getTimeZone();
        int zonediff = serverzone - clientzone;
        Date start = DateUtils.getFormateDate(strStartTime, "dd/MM/yyyy HH:mm:ss");
        Date end = DateUtils.getFormateDate(strEndTime, "dd/MM/yyyy HH:mm:ss");
        CalendarPO c = calendarManager.getCalendar(Long.parseLong(Id));
        c.setStartTime(DateUtils.addHours(start, zonediff));
		c.setEndTime(DateUtils.addHours(end, zonediff));
		c.setTimeZone(Integer.parseInt(timezone));
		c.setUpTime(new Date());
		calendarManager.updateCalendar(c);
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("IsSuccess", true);
        map.put("Msg", "the calendar saved");
        JSONObject object = new JSONObject(map);
		Struts2Utils.renderJson(object.toString());
	}
	
	public void quickDeletePersonalCal() {
		String Id = request.getParameter("calendarId");
		calendarManager.deleteCalendar(Long.parseLong(Id));
		Map<String, Object> map = new HashMap<String, Object>();
        map.put("IsSuccess", true);
        map.put("Msg", "the calendar saved");
        JSONObject object = new JSONObject(map);
		Struts2Utils.renderJson(object.toString());
	}
	
	private List<Object[]> ConvertToStringArray(List<CalendarPO> list) {
		List<Object[]> relist = new ArrayList<Object[]>();
		int serverzone = getTimeZone();
		Calendar c = Calendar.getInstance();
		if (list != null && list.size() > 0) {
			for (CalendarPO entity : list) {
				int clientzone = entity.getTimeZone() != 0 ?entity.getTimeZone() : 8;
				int zonediff = clientzone - serverzone;
				c.setTime(entity.getStartTime());
				c.add(Calendar.HOUR_OF_DAY, zonediff);
				entity.setStartTime(c.getTime());
				c.setTime(entity.getEndTime());
				c.add(Calendar.HOUR_OF_DAY, zonediff);
				entity.setEndTime(c.getTime());
				relist.add(new Object[] {
						entity.getId().toString(),
						entity.getSubject(),
						entity.getStartTime().getTime(),
						entity.getEndTime().getTime(),
						entity.getIsAllDayEvent(),
						DateUtils.getFormateDateStr(entity.getStartTime(),
								"yyyy-MM-dd").equals(
								DateUtils.getFormateDateStr(
										entity.getEndTime(), "yyyy-MM-dd")) ? 0
								: 1,
						entity.getInstanceType() == 2 ? 1 : 0,
						entity.getCategory(), 1, entity.getLocation(), entity.getAttendees() });
			}
		}
		return relist;
	}
	
	private static int getTimeZone() {
		TimeZone now = TimeZone.getDefault();
		return now.getRawOffset()/3600000;
	}
	
}
